package com.voja.workoutrandomizer;

import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONObject;
import com.voja.AndroidUtils.Application;
import com.voja.workoutrandomizer.repository.Exercise;
import com.voja.workoutrandomizer.repository.Workout;
import com.voja.workoutrandomizer.repository.Workouts;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

public class Main extends Activity {

	public static Workouts workouts;
	
	private ProgressBar throbber;
	private ListView    listWorkouts;
	private TextView    tvError;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		Application.setContext(this);
		throbber     = (ProgressBar)findViewById(R.id.throbber);
		listWorkouts = (ListView)findViewById(R.id.listWorkouts);
		tvError      = (TextView)findViewById(R.id.tvError);
	
		LoadDataTask.getInstance(this).execute();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.main, menu);
		
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_settings:
			break;
		}
		
		return super.onOptionsItemSelected(item);
	}
	
	public void dataLoaded() {
		try {
			JSONArray workoutDefinitions = workouts.getDefinitions();
			ArrayList<Workout> workouts = new ArrayList<Workout>();
			JSONObject def;
			for (int i=0; i<workoutDefinitions.length(); i++) {
				def = workoutDefinitions.getJSONObject(i);
				workouts.add(new Workout(def));
			}
			WorkoutsAdapter adapter = new WorkoutsAdapter(this, R.layout.workout_list_item, workouts);
			listWorkouts.setAdapter(adapter);
			listWorkouts.setOnItemClickListener(new OnWorkoutItemClick(this));
			
		} catch (Exception e) {
			e.printStackTrace();
			error(e.getClass().getSimpleName() + ": " + e.getMessage());
		}
	}
	
	public void error(String message) {
		tvError.setText(message);
		tvError.setVisibility(View.VISIBLE);
	}
	
	protected void throbberShow() {
		throbber.setVisibility(View.VISIBLE);
	}
	
	protected void throbberHide() {
		throbber.setVisibility(View.GONE);
	}
}
